package com.hightrast.service.component;


import com.alibaba.fastjson.JSONObject;
import com.hightrast.service.api.domain.bo.ShopifyOrdersResultEntity;
import com.hightrast.service.api.domain.bo.ShopifyProductResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Component
@Slf4j
public class ShopifyApiComponent {


    @Resource
    RestTemplate restTemplate;

    /**
     * 同步商品列表
     */
    public ShopifyProductResultEntity syncProducts() {
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Accept", "application/json");
            httpHeaders.set("Content-Type", "application/json");
            httpHeaders.add("X-Shopify-Access-Token", "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");
            HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
            ResponseEntity<ShopifyProductResultEntity> responseEntity = restTemplate.exchange("https://Hightrast.myshopify.com/admin/api/2025-01/products.json", HttpMethod.GET, httpEntity, ShopifyProductResultEntity.class);
            log.info("获取shopify商品列表结果：{}",JSONObject.toJSONString(responseEntity));
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("同步商品列表，异常：{}", e);
            // 同步商品列表异常
            //throw new ServiceException("Synchronized Product List Exception");
            return null;
        }
    }

    /**
     * 同步订单列表
     */
    public ShopifyOrdersResultEntity syncOrders() {
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Accept", "application/json");
            httpHeaders.set("Content-Type", "application/json");
            httpHeaders.add("X-Shopify-Access-Token", "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");
            // 创建请求体
            HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
            ResponseEntity<ShopifyOrdersResultEntity> responseEntity = restTemplate.exchange("https://Hightrast.myshopify.com/admin/api/2025-01/products.json?status=any", HttpMethod.GET, httpEntity, ShopifyOrdersResultEntity.class);
            log.info("获取shopify订单列表结果：{}",JSONObject.toJSONString(responseEntity));
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("同步订单列表，异常：{}", e);
            //throw new ServiceException("Synchronized Product List Exception");
            return null;
        }
    }
}
